using System.Collections.Generic;
using System.Threading.Tasks;
using ERP.WorkforceManage;
using ERP.WorkforceManage.Dtos;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc;
using System;
using System.Linq;

namespace ERP.Web.Controllers
{
    /// <summary>
    /// 班组管理控制器
    /// </summary>
    public class TeamController : AbpController
    {
        private readonly ITeamService _teamService;

        public TeamController(ITeamService teamService)
        {
            _teamService = teamService;
        }

        /// <summary>
        /// 班组管理页面
        /// </summary>
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 添加/编辑班组页面
        /// </summary>
        public async Task<IActionResult> AddEdit(int? id)
        {
            TeamDto model = null;
            if (id.HasValue)
            {
                model = await _teamService.GetAsync(id.Value);
            }
            return View(model);
        }

        /// <summary>
        /// 获取班组列表
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> GetList([FromBody] GetTeamInputDto input)
        {
            try
            {
                // 确保input不为null
                if (input == null)
                {
                    input = new GetTeamInputDto();
                }

                // 确保maxResultCount有一个合理的值
                if (input.MaxResultCount <= 0)
                {
                    input.MaxResultCount = 100; // 设置默认值
                }

                var result = await _teamService.GetListAsync(input);
                return Json(new { code = 0, msg = "success", data = result.Items, count = result.TotalCount });
            }
            catch (System.Exception ex)
            {
                // 记录错误信息方便调试
                var errorMsg = $"获取班组列表失败: {ex.Message}";
                if (ex.InnerException != null)
                {
                    errorMsg += $" 内部异常: {ex.InnerException.Message}";
                }
                
                return Json(new { code = 1, msg = errorMsg, data = new List<object>(), count = 0 });
            }
        }

        /// <summary>
        /// 获取班组列表(GET方法支持)
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetAllTeams(int skipCount = 0, int maxResultCount = 100, 
            string teamNumber = "", string teamName = "", string teamType = "")
        {
            try
            {
                var input = new GetTeamInputDto
                {
                    SkipCount = skipCount,
                    MaxResultCount = maxResultCount > 0 ? maxResultCount : 100,
                    TeamNumber = teamNumber ?? "",
                    TeamName = teamName ?? "",
                    TeamType = teamType ?? ""
                };

                var result = await _teamService.GetListAsync(input);
                return Json(new { code = 0, msg = "success", data = result.Items, count = result.TotalCount });
            }
            catch (System.Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message, data = new List<object>(), count = 0 });
            }
        }

        /// <summary>
        /// 获取班组详情
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> Get(int id)
        {
            try
            {
                var result = await _teamService.GetAsync(id);
                return Json(new { code = 0, msg = "success", data = result });
            }
            catch (System.Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message });
            }
        }

        /// <summary>
        /// 创建班组
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Create([FromBody] CreateTeamDto input)
        {
            try
            {
                // 验证输入数据
                if (string.IsNullOrWhiteSpace(input?.TeamName))
                {
                    return Json(new { code = 1, msg = "班组名称不能为空" });
                }

                var result = await _teamService.CreateAsync(input);
                return Json(new { code = 0, msg = "创建成功", data = result });
            }
            catch (System.Exception ex)
            {
                // 记录详细错误信息
                var errorMsg = $"创建班组失败: {ex.Message}";
                if (ex.InnerException != null)
                {
                    errorMsg += $" 内部异常: {ex.InnerException.Message}";
                }
                return Json(new { code = 1, msg = errorMsg });
            }
        }

        /// <summary>
        /// 更新班组
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Update(int id, [FromBody] UpdateTeamDto input)
        {
            try
            {
                // 验证输入数据
                if (string.IsNullOrWhiteSpace(input?.TeamName))
                {
                    return Json(new { code = 1, msg = "班组名称不能为空" });
                }

                var result = await _teamService.UpdateAsync(id, input);
                return Json(new { code = 0, msg = "更新成功", data = result });
            }
            catch (System.Exception ex)
            {
                // 记录详细错误信息
                var errorMsg = $"更新班组失败: {ex.Message}";
                if (ex.InnerException != null)
                {
                    errorMsg += $" 内部异常: {ex.InnerException.Message}";
                }
                return Json(new { code = 1, msg = errorMsg });
            }
        }

        /// <summary>
        /// 删除班组
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Delete(int id)
        {
            try
            {
                await _teamService.DeleteAsync(id);
                return Json(new { code = 0, msg = "删除成功" });
            }
            catch (System.Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message });
            }
        }

        /// <summary>
        /// 获取用户选择列表
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> GetUserSelectList([FromBody] GetUserSelectInputDto input)
        {
            try
            {
                var result = await _teamService.GetUserSelectListAsync(input);
                return Json(new { code = 0, msg = "success", data = result.Items, count = result.TotalCount });
            }
            catch (System.Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message });
            }
        }

        /// <summary>
        /// 生成班组编号
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GenerateTeamNumber()
        {
            try
            {
                var result = await _teamService.GenerateTeamNumberAsync();
                return Json(new { code = 0, msg = "success", data = result });
            }
            catch (System.Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message });
            }
        }

        /// <summary>
        /// 用户选择页面
        /// </summary>
        public IActionResult UserSelect(string selectedIds)
        {
            ViewBag.SelectedIds = selectedIds ?? "";
            return View();
        }

        /// <summary>
        /// 获取选中用户的详细信息
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> GetSelectedUsersInfo([FromBody] GetSelectedUsersInfoDto input)
        {
            try
            {
                var result = await _teamService.GetSelectedUsersInfoAsync(input.UserIds);
                return Json(new { code = 0, msg = "success", data = result });
            }
            catch (System.Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message });
            }
        }
    }

    /// <summary>
    /// 获取选中用户信息输入DTO
    /// </summary>
    public class GetSelectedUsersInfoDto
    {
        public List<int> UserIds { get; set; } = new List<int>();
    }
} 